package com.cjb.controller;

import cn.hutool.core.util.RandomUtil;
import com.cjb.entity.Menu;
import com.cjb.response.Result;
import com.cjb.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author kuangjian
 * @since 2022-08-30
 */
@Api(tags = "菜单权限接口")
@CrossOrigin
@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation(value = "加载菜单树",notes = "获取所有菜单树，以及所有展开项")
    @GetMapping("/tree")
    public Result tree(){
        //查询所有菜单
        List<Menu> menuTree = menuService.findMenuTree();
        //查询那些菜单可以展开
        List<Long> openIds = menuService.findOpenIds();
        Map<String,Object> map=new HashMap<>();
        map.put("menuTree",menuTree);
        map.put("ids",openIds);
        return Result.ok().data(map);
    }

    /**
     * 设置验证码
     * @return
     */
    @PostMapping("/setCode")
    public  Result setCode(){
        String code = RandomUtil.randomNumbers(6);
        redisTemplate.opsForValue().set("code",code,10, TimeUnit.SECONDS);

        return Result.ok().data("code",code);
    }
    @GetMapping("/getCode")
    public  Result getCode(){
        Object code = redisTemplate.opsForValue().get("code");
        if(code==null){
            return Result.error().message("验证码已经过期");
        }
        return Result.ok().data("code",code);
    }

}
